package com.fh.shop.api.job.biz;

import com.fh.shop.api.job.mapper.StockWarningMapper;
import com.fh.shop.util.MailUtil;
import com.fh.shop.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
@Slf4j
public class StockWarning {
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private StockWarningMapper stockWarningMapper;
    @Value("${stock.warning.stock}")
    private int stock;
    @Value("${stock.warning.title}")
    private String title;
    @Value("${stock.warning.mail}")
    private String mail;
    @Value("${stock.warning.appendix}")
    private List<String> filePathList;

//    @Scheduled(cron = "0/30 * * * * ?")
    public void stockWarning(){

        //提醒发送邮件
        log.debug("发送邮件===================");

        //查询
        List<Product> productList = stockWarningMapper.queryProductStock(stock);
        if (productList.size() == 0){
            mailUtil.sendMail(mail,title,"没有库存数量小于10的");
//            throw new RuntimeException("没有库存数量小于10的");
        }else {
            //拼接内容
            StringBuilder concat = getConcat(productList);

            //发送邮件
//        mailUtil.sendMail(mail,title,concat.toString());
            mailUtil.sendMailAppendix(mail,title,concat.toString(),filePathList);
        }

        log.debug("发送成功===================");

    }

    private StringBuilder getConcat(List<Product> productList) {
        StringBuilder sb = new StringBuilder();
        sb.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\" style=\"width: 500px;text-align: center;background: #85f5d7\">\n" +
                "        <tr style=\"height: 60px\">\n" +
                "            <td>商品名</td>\n" +
                "            <td>商品价格</td>\n" +
                "            <td>商品库存</td>\n" +
                "            <td>品牌</td>\n" +
                "            <td>分类名</td>\n" +
                "        </tr>\n" );
        for (Product product : productList) {
            sb.append(
                    "        <tr style=\"height: 60px\">\n" +
                    "            <td>"+product.getProductName()+"</td>\n" +
                    "            <td>"+product.getPrice().toString()+"</td>\n" +
                    "            <td>"+product.getStock()+"</td>\n" +
                    "            <td>"+product.getBrandName()+"</td>\n" +
                    "            <td>"+product.getCateName()+"</td>\n" +
                    "        </tr>\n" );
        }

        sb.append("</table>");
        return sb;
    }
}
